package com.cyclingAssistant.project;

import java.util.Arrays;
import java.util.List;

import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.MyLocationOverlay;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.cyclingAssistant.util.Geocoder;

public class RoutePlan extends Activity {
	private static final String[] preferences1 = { "shortest path",
			"least incline", "most scenic", "least pollution", "choose for me" };
	private static final String[] preferences2 = { "none", "shortest path",
			"least incline", "most scenic", "least pollution", "choose for me" };
	private List<String> list1;
	private List<String> list2;
	private Spinner pref1, pref2;
	private ArrayAdapter<String> adapter;
	public static EditText from, to;
	private CheckBox roundtrip;
	private Button submit;
	private ImageButton fromOnMap, toOnMap, fromCurr, toCurr, fromAddr, toAddr;
	private static String description = "";
	private AlertDialog showAddresses1, showAddresses2;
	private TextView roundtrip_desc;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.route_plan);

		from = (EditText) findViewById(R.id.edit_direction_from);
		to = (EditText) findViewById(R.id.edit_direction_to);
		roundtrip = (CheckBox) findViewById(R.id.round_trip_check);
		pref1 = (Spinner) findViewById(R.id.preference1);
		pref2 = (Spinner) findViewById(R.id.preference2);
		submit = (Button) findViewById(R.id.button_show_route);
		fromOnMap = (ImageButton) findViewById(R.id.click_route_from);
		toOnMap = (ImageButton) findViewById(R.id.click_route_to);
		fromCurr = (ImageButton) findViewById(R.id.whereami_route_from);
		toCurr = (ImageButton) findViewById(R.id.whereami_route_to);
		fromAddr = (ImageButton) findViewById(R.id.addressbook_route_from);
		toAddr = (ImageButton) findViewById(R.id.addressbook_route_to);
		roundtrip_desc = (TextView) findViewById(R.id.roundtrip_time);
		
		/************************ drop down menus ********************/
		if (savedInstanceState!=null) {
			Log.v("not null", "not null");
			from.setText(savedInstanceState.getString("from"));
		}
		
		
		/************************ drop down menus ********************/

		// 第一步：添加一个下拉列表项的list，这里添加的项就是下拉列表的菜单项
		list1 = Arrays.asList(preferences1);
		list2 = Arrays.asList(preferences2);

		// 第二步：为下拉列表定义一个适配器，这里就用到里前面定义的list。
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list1);
		// 第三步：为适配器设置下拉列表下拉时的菜单样式。
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 第四步：将适配器添加到下拉列表上
		pref1.setAdapter(adapter);
		// pref1.setVisibility(View.VISIBLE);

		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list2);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		pref2.setAdapter(adapter);


		/************************ get directions ********************/

		submit.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				CyclingAssistantActivity.mapView.getOverlays().clear();
				Intent intent = new Intent("com.cyclingAssistant.main");
				intent.putExtra("from", from.getText().toString());
				intent.putExtra("to", to.getText().toString());
				intent.putExtra("round-trip", roundtrip.isChecked());
				intent.putExtra("pref1",
						preferences1[pref1.getSelectedItemPosition()]);
				intent.putExtra("pref2",
						preferences2[pref2.getSelectedItemPosition()]);
				Log.v("in route plan: from", from.getText().toString());

				RoutePlan.this.sendBroadcast(intent);

				TabHost tabHost = (TabHost) TabMenu.tabHost;
				tabHost.setCurrentTab(0);
			}
		});

		/************************ current location ********************/
		fromCurr.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final MapView mapView = CyclingAssistantActivity.mapView;
				final MyLocationOverlay me = new MyLocationOverlay(
						RoutePlan.this, mapView);
				me.enableMyLocation();
				me.runOnFirstFix(new Runnable() {
					public void run() {
						GeoPoint point = me.getMyLocation();
						description = Geocoder.getFormattedAddress(
								point.getLatitudeE6() / 1E6,
								point.getLongitudeE6() / 1E6);
					}
				});
				from.setText(description);
				from.invalidate();
			}
		});

		toCurr.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final MapView mapView = CyclingAssistantActivity.mapView;
				final MyLocationOverlay me = new MyLocationOverlay(
						RoutePlan.this, mapView);
				me.enableMyLocation();
				me.runOnFirstFix(new Runnable() {
					public void run() {
						GeoPoint point = me.getMyLocation();
						description = Geocoder.getFormattedAddress(
								point.getLatitudeE6() / 1E6,
								point.getLongitudeE6() / 1E6);
					}
				});
				to.setText(description);
				to.invalidate();
			}
		});

		/************************ click to get location ********************/
		CyclingAssistantActivity.overlayFrom.text = from;
		CyclingAssistantActivity.overlayTo.text = to;
		fromOnMap.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				MapView mapView = CyclingAssistantActivity.mapView;
				mapView.getOverlays().clear();
				mapView.getOverlays().add(CyclingAssistantActivity.overlayFrom);

				Toast t = Toast.makeText(RoutePlan.this, "click map to specify the point", Toast.LENGTH_SHORT);
				t.setGravity(Gravity.TOP|Gravity.CENTER, 0, 50); 
				t.show();
				TabHost tabHost = (TabHost) TabMenu.tabHost;
				tabHost.setCurrentTab(0);
			}
		});

		toOnMap.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				MapView mapView = CyclingAssistantActivity.mapView;
				mapView.getOverlays().clear();
				mapView.getOverlays().add(CyclingAssistantActivity.overlayTo);

				TabHost tabHost = (TabHost) TabMenu.tabHost;
				tabHost.setCurrentTab(0);
			}
		});

		/************************ get location from address book ********************/
		final String[] items = { "UBC", "Home", "Stanley Park" };
		final ListView list1 = new ListView(this);
		list1.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, items));
		list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				from.setText(items[arg2]);
				showAddresses1.dismiss();
			}
		});

		final ListView list2 = new ListView(this);
		list2.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, items));
		list2.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				to.setText(items[arg2]);
				showAddresses2.dismiss();
			}
		});
		
		
		/************************ show roundtrip options ********************/
		roundtrip.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if (roundtrip.isChecked()) { // 勾上这个checkBox 对应的动作
					enableDisableView(findViewById(R.id.direction_to), false);
					showRoundTripOptions();
				} else {
					enableDisableView(findViewById(R.id.direction_to), true);
					roundtrip_desc.setVisibility(View.GONE);
				}

			}
		});
		

		/************************ from address book**********************/
		fromAddr.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog1(list1);
			}
		});

		toAddr.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog2(list2);
			}
		});

	}

	protected void showDialog1(View textEntry) {
		if (showAddresses1==null) {
			AlertDialog.Builder builder = new Builder(this);
			// builder.setCancelable(false);
			builder.setTitle("Choose an address");
			builder.setView(textEntry);
			showAddresses1 = builder.create();
		}
		showAddresses1.show();
	}
	
	protected void showDialog2(View textEntry) {
		if (showAddresses2==null) {
			AlertDialog.Builder builder = new Builder(this);
			// builder.setCancelable(false);
			builder.setTitle("Choose an address");
			builder.setView(textEntry);
			showAddresses2 = builder.create();
		}
		showAddresses2.show();
	}
	protected void showRoundTripOptions() {
		LayoutInflater inflater = LayoutInflater.from(this);
		final View textEntry = inflater.inflate(R.layout.roundtrip_options, null);

		final EditText hour = (EditText) textEntry.findViewById(R.id.hour_picked);
		final EditText min = (EditText) textEntry.findViewById(R.id.min_picked);

		final AlertDialog.Builder builder = new Builder(this);
		// builder.setCancelable(false);
		builder.setTitle("Round-trip Options");
		builder.setView(textEntry);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				String s = "round-trip time: " + hour.getText().toString() + " hours, " + min.getText().toString() +" minutes";
				roundtrip_desc.setText(s);
				roundtrip_desc.setVisibility(View.VISIBLE);
			}
		});
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub

			}
		});
		builder.show();
		
	}
	private void enableDisableView(View view, boolean enabled) {
		view.setEnabled(enabled);

		if (view instanceof ViewGroup) {
			ViewGroup group = (ViewGroup) view;

			for (int idx = 0; idx < group.getChildCount(); idx++) {
				enableDisableView(group.getChildAt(idx), enabled);
			}
		}
	}
//
//	@Override
//	protected void onSaveInstanceState(Bundle saveInstallState) {
//		saveInstallState.putString("from", from.getText().toString());
//		Log.v("saved", from.getText().toString());
//		super.onSaveInstanceState(saveInstallState);
//	}
//
//	@Override
//	protected void onRestoreInstanceState(Bundle savedInstanceState) {
//		super.onRestoreInstanceState(savedInstanceState);
//	}
//	@Override
//	public void onStop()
//	{
//		Log.v("stoped", "activity stoped");
//		super.onStop();
//	}
//	@Override
//	public void onDestroy()
//	{
//		Log.v("destroyed", "activity destroyed");
//		super.onStop();
//	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
//	        moveTaskToBack(true);
//	        return true;
	    	Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 注意
			intent.addCategory(Intent.CATEGORY_HOME);
			this.startActivity(intent);
			return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
}
